#
# MP4Track.py
#
# This work is released under the GNU GPL, version 2 or later.
#
from Track import *
from time import *
import os,time
from mp4Info import *
#import traceback
from Utils.Settings import *
from Utils.utils import *

class MP4Track(XineTrack):
	def __init__(self,library = None):
		XineTrack.__init__(self,library)
	
	#
	# load any ID3 tags that are contained in the MP3 file
	#
	def setFile(self,filePath,thread = None):
		global stream
		if type(filePath).__name__=='unicode':
			filePath = filePath.encode('latin-1')
		stats = os.stat(filePath)
		self.size = stats[6]
		self.location = filePath
		(srcPath,fileName) = os.path.split(filePath)
		(rootName,extension) = os.path.splitext(fileName)
		self.title = rootName
		try:
			info = MP4Info(open(filePath,"rb"))
			tags = info.info()
			try: self.title = unikode(tags['Title'])
			except: pass
			try: self.artist = unikode(tags['Artist'])
			except: pass
			try: self.album = unikode(tags['Album'])
			except: pass
			try: self.composer = unikode(tags['Composer'])
			except: pass
			try: self.contentType = tags['Content Type']
			except: pass
			try: self.year = tags['Year']
			except: pass
			try: self.encodedBy = tags['Encoder']
			except: pass
			try: self.dateEncoded = time.gmtime(tags['Creation Time']) #strptime(tags['Creation Time'],"%Y-%m-%dT%H:%M:%S")
			except: pass
			try: self.dateModified =  time.gmtime(tags['Modification Time']) #strptime(tags['Creation Time'],"%Y-%m-%dT%H:%M:%S")
			except: pass
			try: self.trackNum = int(tags['Track Number'][0])
			except: pass
			try: self.trackCount = tags['Track Number'][1]
			except: pass
			try: self.discNum =int( tags['Disc Number'][0])
			except: pass
			try: self.discCount = tags['Disc Number'][1]
			except: pass
			self.kind = "MPEG-4 audio file"
			try: self.bitRate = tags['Bit Rate']
			except: pass
			try: self.sampleRate = tags['Sample Rate']
			except: pass
			try: self.format = "MPEG-%d, Layer %d" % (tags['MPEG Version'],tags['Layer'])
			except: pass
			try: self.channels = tags['Channels']
			except: pass
			try: self.totalTime = int(tags['Duration']*1000)
			except: pass
			try: self.compilation = tags['Compilation']
			except: pass
			try: self.contentType = "(%d)" % (tags['Genre']-1)
			except: pass
		except: pass
	file = property(None,setFile)

	#
	# fetch the (first) artwork for this track
	#
	def getImage(self):
		filePath = self.location
		#print "attempting to get art from",self.location
		try:
			#print "getting tags from",filePath
			info = MP4Info(open(filePath,"rb"),True)
			tags = info.info()
			return tags['Cover Art']
		except:
			#traceback.print_stack()
			return None
	image = property(getImage)		
		
